using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using IPC.WinForm.Bussiness;

namespace IPC.WinForm
{
    internal static class Program
    {

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Process currentProcess = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            bool singleInstance = false;
            System.Threading.Mutex singleInstanceMutex = new System.Threading.Mutex(true, "IPC.WinForm", out singleInstance);
            if (!singleInstance)
            {
                IntPtr handle = FindWindow(null, "IPC");
                ShowWindowAsync(handle, 1);
                SetForegroundWindow(handle);
                Application.Exit();
            }
            else
            {
                string localhostIP = "";
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localhostIP = ip.ToString();
                        if (ConfigDbBussiness.Instance.GetConfigByKey("localhostIP") == "")
                        {
                            ConfigDbBussiness.Instance.UpdateConfig("localhostIP", localhostIP);
                        }
                        break;
                    }
                }
                //delegateCommand = mainViewModel.StopService;
                //Task.Run(() => StartWebServer());
                ApplicationConfiguration.Initialize();
                
                Application.Run(new FrmMain());
            }
        }

        private static WebApplication app = null;

        private static void StartWebServer()
        {
            var builder = WebApplication.CreateBuilder();

            // Add services to the container.
            
            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            //app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            string ip = ConfigDbBussiness.Instance.GetConfigByKey("localhostIP");
            string port = ConfigDbBussiness.Instance.GetConfigByKey("Port","9099");
            app.Run($"http://{ip}:{port}/");
            app.DisposeAsync();
            //app.StopAsync();
        }
    }
}